//
//  PKRequestManager.m
//  PianKe
//
//  Created by lanou on 15/12/22.
//  Copyright © 2015年 MaZeGong. All rights reserved.
//

#import "OSRequestManager.h"

@implementation OSRequestManager
// 实现网络请求类的方法
+ (void)requestWithUrlString:(NSString *)urlString parDic:(NSDictionary *)parDic method:(RequestType)method finish:(Finish)finish error:(Error)errors view:(UIView *)view{
    if ([RMMFileManager isNetwork]) {
        [RMMFileManager MBProgressWith:@"请检查网络是否连接!" onView:view];
        return;
    }
    [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleFade];
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:view];
    if (view) {
        [view addSubview:hud];
        [hud show:YES];
        hud.mode = MBProgressHUDModeIndeterminate;
    }
   // hud.color = [RGBA(127, 128, 128, 1) colorWithAlphaComponent:0.9];
    // 创建一个网络链接
    NSString *timersTemp = [RMMFileManager getTimesTamp];
    NSString *sign = [RMMFileManager getMD5WithString:timersTemp];
    NSString *url = nil;
    if (method == POST) {
        url = [NSString stringWithFormat:@"%@%@?timestamp=%@&appid=%@&sign=%@",kBaseUrl,urlString,timersTemp,APPID,sign];
    } else {
        url = [NSString stringWithFormat:@"%@%@?timestamp=%@&appid=%@&sign=%@",kBaseUrl,urlString,timersTemp,APPID,sign];
        for (NSString *key in parDic) {
            NSString *value = parDic[key];
            url = [NSString stringWithFormat:@"%@&%@=%@",url,key,value];
        }
        url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    }
    NSLog(@"%@",url);
//    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
//    manger.responseSerializer = [AFHTTPResponseSerializer serializer];
//    [manger.requestSerializer willChangeValueForKey:@"willChange"];
//    manger.requestSerializer.timeoutInterval = 15.f;
//    [manger.requestSerializer didChangeValueForKey:@"didChange"];
//    if (method == POST) {
//        url = [NSString stringWithFormat:@"%@%@?timestamp=%@&appid=%@&sign=%@",kBaseUrl,urlString,timersTemp,APPID,sign];
//        [manger POST:url parameters:parDic progress:^(NSProgress * _Nonnull uploadProgress) {
//            
//        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
//            [hud hide:YES];
//            if (dataDic == nil) {
//                [RMMFileManager MBProgressWith:@"未知数据类型错误!" onView:view];
//                return ;
//            }
//            finish(dataDic);
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            [hud hide:YES];
//            [RMMFileManager MBProgressWith:@"数据加载错误!" onView:view];
//            errors(error); // 函数的调用
//        }];
//    } else {
//        url = [NSString stringWithFormat:@"%@%@&timestamp=%@&appid=%@&sign=%@",kBaseUrl,urlString,timersTemp,APPID,sign];
//        [manger GET:url parameters:parDic progress:^(NSProgress * _Nonnull downloadProgress) {
//            
//        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
//            [hud hide:YES];
//            if (dataDic == nil) {
//                [RMMFileManager MBProgressWith:@"未知数据类型错误!" onView:view];
//                return ;
//            }
//            finish(dataDic);
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            [hud hide:YES];
//            [RMMFileManager MBProgressWith:@"数据加载错误!" onView:view];
//            errors(error); // 函数的调用
//        }];
//    }
   // 创建一个网络请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:15];
    // 判断网络请求的类型
    if (method == POST) {
        // 设置网络请求表示
        [request setHTTPMethod:@"POST"];
        NSData *postData = [NSJSONSerialization dataWithJSONObject:parDic options:NSJSONWritingPrettyPrinted error:nil];
        [request setHTTPBody:postData];
    }
    // block 数据解析
//    NSURLSession *session = [NSURLSession sharedSession];
//     NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//         if (error == nil) {
//             NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
//             dispatch_async(dispatch_get_main_queue(), ^{
//                 [hud hide:YES];
//             });
//             finish(dataDic);
//             NSLog(@"%@",[NSThread currentThread]);
//         } else {
//             [hud hide:YES];
//             [CKFileManager MBProgressWith:@"加载超时,请重新加载!" onView:view];
//             errors(error); // 函数的调用
//         }
//
//    }];
 //   [task resume];
    // 已经不建议使用了
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [hud hide:YES];
        if (connectionError == nil) {
            NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            if (dataDic == nil) {
                [RMMFileManager MBProgressWith:@"未知数据类型错误!" onView:view];
                return ;
            }
            finish([RMMFileManager setValueForDic:dataDic]);
         } else {
            [hud hide:YES];
             [RMMFileManager MBProgressWith:@"加载超时,请重新加载!" onView:view];
            errors(connectionError); // 函数的调用
        }
    }];
}
+ (void)requestNoProgressWithUrlString:(NSString *)urlString parDic:(NSDictionary *)parDic method:(RequestType)method finish:(Finish)finish error:(Error)errors view:(UIView *)view{
    if ([RMMFileManager isNetwork]) {
        [RMMFileManager MBProgressWith:@"请检查网络是否连接!" onView:view];
        return;
    }
    [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleFade];
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:view];
    if (view) {
        [view addSubview:hud];
        [hud show:YES];
        hud.mode = MBProgressHUDModeIndeterminate;
    }
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    [AFHTTPSessionManager shareHandler].responseSerializer = [AFHTTPResponseSerializer serializer];
    [[AFHTTPSessionManager shareHandler].requestSerializer willChangeValueForKey:@"willChange"];
    [AFHTTPSessionManager shareHandler].requestSerializer.timeoutInterval = 15.f;
    [[AFHTTPSessionManager shareHandler].requestSerializer didChangeValueForKey:@"didChange"];
    if (method == POST) {
        [[AFHTTPSessionManager shareHandler] POST:urlString parameters:parDic progress:^(NSProgress * _Nonnull uploadProgress) {

        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
            [hud hide:YES];
            if (dataDic == nil) {
                [RMMFileManager MBProgressWith:@"未知数据类型错误!" onView:view];
                return ;
            }
            finish(dataDic);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [hud hide:YES];
            [RMMFileManager MBProgressWith:@"数据加载错误!" onView:view];
            errors(error); // 函数的调用
        }];
    } else {
        [[AFHTTPSessionManager shareHandler] GET:urlString parameters:parDic progress:^(NSProgress * _Nonnull downloadProgress) {

        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
            [hud hide:YES];
            if (dataDic == nil) {
                [RMMFileManager MBProgressWith:@"未知数据类型错误!" onView:view];
                return ;
            }
            finish(dataDic);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [hud hide:YES];
            [RMMFileManager MBProgressWith:@"数据加载错误!" onView:view];
            errors(error); // 函数的调用
        }];
    }
}
+ (void)requestFWithUrlString:(NSString *)urlString parDic:(NSDictionary *)parDic method:(RequestType)method finish:(Finish)finish error:(Error)errors view:(UIView *)view{
    if ([RMMFileManager isNetwork]) {
        [RMMFileManager MBProgressWith:@"请检查网络是否连接!" onView:view];
        return;
    }
    [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleFade];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    // hud.color = [RGBA(127, 128, 128, 1) colorWithAlphaComponent:0.9];
    hud.mode = MBProgressHUDModeIndeterminate;
    // 创建一个网络链接
    NSString *timersTemp = [RMMFileManager getTimesTamp];
    NSString *sign = [RMMFileManager getMD5WithString:timersTemp];
    NSString *url = nil;
    if (method == POST) {
        url = [NSString stringWithFormat:@"%@%@?timestamp=%@&appid=%@&sign=%@",kBaseUrl,urlString,timersTemp,APPID,sign];
    } else {
        url = [NSString stringWithFormat:@"%@%@?timestamp=%@&appid=%@&sign=%@",kBaseUrl,urlString,timersTemp,APPID,sign];
        for (NSString *key in parDic) {
            NSString *value = parDic[key];
            url = [NSString stringWithFormat:@"%@&%@=%@",url,key,value];
        }
        url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    }
    NSLog(@"%@",url);
    // 创建一个网络请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:15];
    // 判断网络请求的类型
    if (method == POST) {
        // 设置网络请求表示
        [request setHTTPMethod:@"POST"];
        NSData *postData = [NSJSONSerialization dataWithJSONObject:parDic options:NSJSONWritingPrettyPrinted error:nil];
        [request setHTTPBody:postData];
    }
    // block 数据解析
    //    NSURLSession *session = [NSURLSession sharedSession];
    //     NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    //         if (error == nil) {
    //             NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
    //             dispatch_async(dispatch_get_main_queue(), ^{
    //                 [hud hide:YES];
    //             });
    //             finish(dataDic);
    //             NSLog(@"%@",[NSThread currentThread]);
    //         } else {
    //             [hud hide:YES];
    //             [CKFileManager MBProgressWith:@"加载超时,请重新加载!" onView:view];
    //             errors(error); // 函数的调用
    //         }
    //
    //    }];
    //   [task resume];
    // 已经不建议使用了
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [hud hide:YES];
        if (connectionError == nil) {
            NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            if (dataDic == nil) {
                [RMMFileManager MBProgressWith:@"未知数据类型错误!" onView:view];
                return ;
            }
            NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
            if ([status isEqualToString:@"1"]) {
                finish([RMMFileManager setValueForDic:dataDic]);

            } else {
                [RMMFileManager MBProgressWith:dataDic[@"message"] onView:view];
            }
        } else {
            [hud hide:YES];
            [RMMFileManager MBProgressWith:@"加载超时,请重新加载!" onView:view];
            errors(connectionError); // 函数的调用
        }
    }];
}
+ (void)requestWithUrlString:(NSString *)urlString
                      parDic:(NSDictionary *)parDic
                     network:(Network)isNetwork
                      method:(RequestType)method
                      finish:(Finish)finish
                       error:(Error)error
                        view:(UIView *)view{
    if ([RMMFileManager isNetwork]) {
        [RMMFileManager MBProgressWith:@"请检查网络是否连接!" onView:view];
        isNetwork(NO);
        return;
    } else {
        isNetwork(YES);
    }
    [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleFade];
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:view];
    if (view) {
        [view addSubview:hud];
        [hud show:YES];
        hud.mode = MBProgressHUDModeIndeterminate;
    }
    NSString *timersTemp = [RMMFileManager getTimesTamp];
    NSString *sign = [RMMFileManager getMD5WithString:timersTemp];
    NSString *url = nil;
    if (method == POST) {
        url = [NSString stringWithFormat:@"%@%@?timestamp=%@&appid=%@&sign=%@",kBaseUrl,urlString,timersTemp,APPID,sign];
    } else {
        url = [NSString stringWithFormat:@"%@%@?timestamp=%@&appid=%@&sign=%@",kBaseUrl,urlString,timersTemp,APPID,sign];
        for (NSString *key in parDic) {
            NSString *value = parDic[key];
            url = [NSString stringWithFormat:@"%@&%@=%@",url,key,value];
        }
        url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    }
    NSLog(@"%@",url);
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:15];
    // 判断网络请求的类型
    if (method == POST) {
        // 设置网络请求表示
        [request setHTTPMethod:@"POST"];
        NSData *postData = [NSJSONSerialization dataWithJSONObject:parDic options:NSJSONWritingPrettyPrinted error:nil];
        [request setHTTPBody:postData];
    }
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [hud hide:YES];
        if (connectionError == nil) {
            NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            if (dataDic == nil) {
                [RMMFileManager MBProgressWith:@"未知数据类型错误!" onView:view];
                return ;
            }
            finish([RMMFileManager setValueForDic:dataDic]);
        } else {
            [hud hide:YES];
            [RMMFileManager MBProgressWith:@"加载超时,请重新加载!" onView:view];
            error(connectionError); // 函数的调用
        }
    }];

    
}


@end
